import tkinter as tk
from tkinter import ttk, messagebox
import os
import sys


class ModifyEmployeesWindow:
    def __init__(self, parent, view_window, db_manager, icon_path="asset/OIP-C.ico"):
        self.parent = parent
        self.view_window = view_window
        self.db = db_manager
        self.current_data = {}
        self.icon_path = icon_path  # 新增图标路径属性

        # 初始化窗口
        self.top = tk.Toplevel(parent)
        self.top.title("职工信息修改")
        self.top.geometry("500x450")
        self.top.resizable(False, False)
        self.top.grab_set()

        # 设置窗口图标（新增代码）
        self._set_window_icon()

        # 创建界面组件（保持不变）
        self.create_widgets()

    def _set_window_icon(self):
        """设置窗口图标（新增方法）"""
        if not self.icon_path:
            return

        try:
            # 尝试设置窗口图标
            if sys.platform == "win32":
                self.top.iconbitmap(self.icon_path)
            else:
                # macOS/Linux使用PhotoImage方式
                img = tk.PhotoImage(file=self.icon_path)
                self.top.call('wm', 'iconphoto', self.top._w, img)

        except Exception as e:
            messagebox.showwarning("图标加载失败",
                                   f"图标加载失败：{os.path.basename(self.icon_path)}\n"
                                   f"错误详情：{str(e)}\n"
                                   f"当前路径：{os.path.abspath(self.icon_path)}")

    def create_widgets(self):
        """ 创建修改窗口界面组件 """
        main_frame = ttk.Frame(self.top, padding=20)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 职工号输入区域
        input_frame = ttk.LabelFrame(main_frame, text="职工信息查询", padding=10)
        input_frame.pack(fill=tk.X, pady=5)

        ttk.Label(input_frame, text="职工号：").grid(row=0, column=0, padx=5)
        self.emp_id_entry = ttk.Entry(input_frame, width=20)
        self.emp_id_entry.grid(row=0, column=1, padx=5)
        ttk.Button(
            input_frame,
            text="查询",
            command=self.query_employee,
            width=8
        ).grid(row=0, column=2, padx=5)

        # 信息编辑区域
        edit_frame = ttk.LabelFrame(main_frame, text="职工信息编辑", padding=10)
        edit_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        # 初始化字段结构（三元组：标签文本, 变量, 组件）
        self.fields = {
            "name": ("姓名", tk.StringVar(), None),
            "age": ("年龄", tk.IntVar(), None),
            "gender": ("性别", tk.StringVar(), None),
            "education": ("学历", tk.StringVar(), None),
            "salary": ("薪资", tk.DoubleVar(), None),
            "address": ("地址", tk.StringVar(), None),
            "phone": ("电话", tk.StringVar(), None)
        }

        for i, (field, (label_text, var, _)) in enumerate(self.fields.items()):
            ttk.Label(edit_frame, text=label_text + ":").grid(row=i, column=0, padx=5, pady=2, sticky=tk.E)

            if field == "gender":
                # 性别字段使用下拉框
                combo = ttk.Combobox(
                    edit_frame,
                    textvariable=var,
                    values=["男", "女"],
                    state="readonly",
                    width=23
                )
                combo.grid(row=i, column=1, padx=5, pady=2)
                self.fields[field] = (label_text, var, combo)
            else:
                # 普通字段使用Entry
                entry = ttk.Entry(edit_frame, textvariable=var, width=25)
                entry.grid(row=i, column=1, padx=5, pady=2)
                entry.state(['disabled'])
                self.fields[field] = (label_text, var, entry)

        # 操作按钮区域
        btn_frame = ttk.Frame(main_frame)
        btn_frame.pack(fill=tk.X, pady=10)

        self.submit_btn = ttk.Button(
            btn_frame,
            text="提交修改",
            command=self.submit_changes,
        )
        self.submit_btn.pack(side=tk.RIGHT, padx=5)

        # 样式配置
        style = ttk.Style()
        style.configure("Primary.TButton", foreground="white", background="#007bff")

    def query_employee(self):
        """ 查询职工详细信息 """
        emp_id = self.emp_id_entry.get().strip()
        if not emp_id:
            messagebox.showwarning("输入错误", "职工号不能为空")
            return

        try:
            # 执行查询
            result = self.db.execute_query(
                "SELECT * FROM employee WHERE employee_id = %s",
                (emp_id,),
                fetch_all=True
            )

            if not result:
                messagebox.showwarning("未找到记录", "该职工号不存在")
                self.clear_fields()
                self.submit_btn.state(['disabled'])
                return

            # 填充数据到界面
            self.current_data = result[0]
            for field, (label, var, widget) in self.fields.items():
                if field == "gender":
                    # 设置下拉框的当前值
                    widget.set("男" if self.current_data[field] == "M" else "女")
                else:
                    var.set(self.current_data[field])

                # 启用编辑（排除职工号字段）
                if field != "employee_id":
                    widget.state(['!disabled'])

            self.submit_btn.state(['!disabled'])

        except Exception as e:
            messagebox.showerror("查询失败", f"数据库错误：{str(e)}")

    def clear_fields(self):
        """ 清空所有字段 """
        for field, (label, var, widget) in self.fields.items():
            if field == "gender":
                widget.set("")
            else:
                var.set("")
            widget.state(['disabled'])

    def submit_changes(self):
        """ 提交修改到数据库 """
        emp_id = self.emp_id_entry.get().strip()
        if not emp_id or not self.current_data:
            messagebox.showwarning("操作错误", "请先查询职工信息")
            return

        # 收集修改后的数据（修正后的版本）
        updates = {}
        for field, (label, var, widget) in self.fields.items():
            new_value = var.get()

            # 保持gender字段为中文值
            if field == "gender":
                if new_value not in ["男", "女"]:
                    messagebox.showwarning("输入错误", "性别必须为'男'或'女'")
                    return

            # 跳过未修改的字段和职工号字段
            if field == "employee_id" or new_value == str(self.current_data[field]):
                continue

            updates[field] = new_value

        # 字段验证
        validation_errors = self.validate_fields(updates)
        if validation_errors:
            messagebox.showwarning("验证失败", "\n".join(validation_errors))
            return

        # 执行更新
        try:
            success = self.db.update_employee(emp_id, updates)
            if success:
                messagebox.showinfo("修改成功", "职工信息已更新")
                self.on_close()
                self.view_window.load_data()
            else:
                messagebox.showwarning("修改失败", "未找到该职工号或更新失败")

        except Exception as e:
            messagebox.showerror("修改错误", f"数据库操作失败：{str(e)}")

    def validate_fields(self, updates):
        """ 字段级验证 """
        errors = []
        current_salary = self.current_data.get("salary", 0)

        if "salary" in updates:
            try:
                new_salary = float(updates["salary"])
                if new_salary < current_salary:
                    errors.append("薪资不能降低")
                if new_salary <= 0:
                    errors.append("薪资必须大于0")
            except ValueError:
                errors.append("薪资格式无效")

        if "age" in updates:
            try:
                age = int(updates["age"])
                if age < 18 or age > 65:
                    errors.append("年龄必须在18-65岁之间")
            except ValueError:
                errors.append("年龄必须为整数")

        if "phone" in updates:
            phone = updates["phone"]
            if not phone.isdigit() or len(phone) != 11:
                errors.append("电话号码必须为11位数字")

        if "gender" in updates:
            if updates["gender"] not in ["男", "女"]:
                errors.append("性别必须为'男'或'女'")

        # 添加空值检查
        required_fields = ["name", "gender"]
        for field in required_fields:
            if field in updates and not updates[field].strip():
                errors.append(f"{self.fields[field][0]}不能为空")

        return errors

    def on_close(self):
        """ 窗口关闭处理 """
        self.top.destroy()